#include "diodorspi.h"
#include <libftdi/ftdi.h>
#include "ftdispi.h"
#include <QDebug>

DiodorSpi::DiodorSpi(int vendorId, int productId, int interface, QObject *parent)
    : QThread(parent)
{
    this->productID = productId;
    this->vendorID = vendorId;
    this->interface = interface;
    this->baudrate = 1000000;
    this->started = false;
    this->dataToSend = new QByteArray;
}
DiodorSpi::~DiodorSpi(void)
{
    this->started = false;
    delete this->dataToSend;

}

void DiodorSpi::run()
{
    if(!this->started)
    {
        ftdi_context *ftdi = new ftdi_context;
        //ftdi_set_bitmode()
        //struct ftdispi_context *ftdispi = new ftdispi_context;
        if (ftdi_init(ftdi) < 0)
        {
//            this->setError((char*)"ftdi_init failed\n");
            //return false;
        }
        ftdi_set_interface(ftdi,INTERFACE_ANY);
        ftdi_set_latency_timer(ftdi,1);
        int i = ftdi_usb_open(ftdi, this->vendorID, this->productID);
        if (i < 0 && i != -5)
        {
            //this->setError(ftdi_get_error_string(ftdi));
            //return false;
        }
        ftdi_set_bitmode(ftdi,0,BITMODE_SYNCFF);
        ftdi_set_baudrate(ftdi,57600);
#define MAX_PKG_SIZE 800
        unsigned char buf[MAX_PKG_SIZE];
        for (int i=0;i<MAX_PKG_SIZE;i++)
        {
            buf[i]=i;
        }
        this->started = true;
/*        ftdispi_open(ftdispi, ftdi, this->interface);
        ftdispi_setmode(ftdispi, 1, 0, 0, 0, 0, 0);
        ftdispi_setclock(ftdispi, 15000000);
        ftdispi_setloopback(ftdispi, 0);


        unsigned char buf[MAX_PKG_SIZE];
        int size = 0;*/
        while(this->started)
        {
            ftdi_write_data(ftdi,buf,MAX_PKG_SIZE);
            //emit(SIGNAL(dataRecive(QByteArray(buf,8000))));
        }
        ftdi_usb_reset(ftdi);
        ftdi_usb_close(ftdi);
    }
}


void DiodorSpi::dataSend(QByteArray data)
{
    this->dataToSend->append(data);
}
